package com.kun.config;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kun.entity.SysUser;
import com.kun.util.LoginUserContext;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 自动填充属性
 * @author kun.li
 */
public class DefaultMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        SysUser user = LoginUserContext.getUser();
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
        this.strictInsertFill(metaObject, "updateTime", Date::new, Date.class);
        if (ObjUtil.isNotEmpty(user)){
            this.strictInsertFill(metaObject, "createBy", user::getUsername,String.class) ;
            this.strictInsertFill(metaObject, "updateBy", user::getUsername,String.class) ;
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SysUser user = LoginUserContext.getUser();
        if (ObjUtil.isNotEmpty(user)){
            this.strictInsertFill(metaObject, "updateTime", Date::new, Date.class);
            this.strictInsertFill(metaObject, "updateBy", user::getUsername,String.class) ;
        }

    }
}
